<template>
  <div class="email-send-container">
    <el-form :model="form" label-width="80px" class="email-form">
      <el-form-item label="邮箱">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      <div class="code-row">
        <el-form-item label="验证码" class="code-input-item">
          <el-input v-model="form.code" placeholder="请输入验证码" />
        </el-form-item>
        <el-button
          type="primary"
          class="send-btn"
          :disabled="sending"
          @click="sendCode"
        >
          <template v-if="sending">{{ countdown }}秒后可重发</template>
          <template v-else>发送验证码</template>
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRegisterStore } from '@/stores/auth/register'
const registerStore = useRegisterStore()
const form = ref({
  email: '',
  code: ''
})

const sending = ref(false)
const countdown = ref(60)
let timer: number | null = null

const sendCode = async() => {
  
  if (!form.value.email) {
    ElMessage.error('请输入邮箱')
    return
  }
  // TODO: 调用接口发送验证码
    const emailRegex = /^[\w-.]+@[\w-]+(\.[\w-]+)+$/
    if (!emailRegex.test(form.value.email)) {
      ElMessage.error('请输入有效的邮箱地址')
      return false
    }

  try {
    await registerStore.sendVerificationCode(form.value.email, 'register')
  } catch (error) {
    ElMessage.error('发送验证码失败，请稍后重试')
    return
  }

  ElMessage.success('验证码已发送')
  sending.value = true
  countdown.value = 60
  timer && clearInterval(timer)
  timer = window.setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      sending.value = false
      timer && clearInterval(timer)
      timer = null
    }
  }, 1000)
}

// 防止组件卸载时定时器未清理
import { onUnmounted } from 'vue'
onUnmounted(() => {
  timer && clearInterval(timer)
})

 async function verify(){
  if(!form.value.email){
    ElMessage.error('请输入邮箱')
    return false
  }
    const emailRegex = /^[\w-.]+@[\w-]+(\.[\w-]+)+$/
    if (!emailRegex.test(form.value.email)) {
      ElMessage.error('请输入有效的邮箱地址')
      return false
    }

  if(!form.value.code){
    ElMessage.error('请输入验证码')
    return false
  }
  try{
      await registerStore.validateCode(form.value.email, form.value.code, 'REGISTER')
      registerStore.setEmail(form.value.email)
  }
  catch(error){
    ElMessage.error((error as Error).message || '验证码验证失败')
    return false
  }
  return true
 }

 defineExpose({
  verify
 })

</script>

<style scoped>
.email-send-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 32px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}
.email-form {
  width: 100%;
}
.code-row {
  display: flex;
  align-items: center;
  gap: 16px;
}
.code-input-item {
  flex: 1;
  margin-bottom: 0;
}
.send-btn {
  white-space: nowrap;
}
</style>
